package financier.jfz.com.babycare.base;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

public class BaseViewGroup extends LinearLayout {
    GroupAdapter adapter;


    public BaseViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        initUI();
    }

    private void initUI() {
    }

    public void setAdapter(GroupAdapter adapter) {
        removeAllViews();
        this.adapter = adapter;
        adapter.clear();
        int size = adapter.count();
        for (int i = 0; i < size; i++) {
            GroupHolder holder = adapter.getHolder(this);
            addView(holder.ItemView);
            holder.position = i;
            adapter.bind(i, holder);
        }
    }

    public BaseViewGroup(Context context) {
        this(context, null);
    }

    public static abstract class GroupAdapter<T extends GroupHolder> {
        private List<T> holders = new ArrayList<>();

        protected void clear() {
            holders.clear();
        }

        protected abstract int count();

        protected abstract T creatHolder(ViewGroup parent);

        T getHolder(ViewGroup parent) {
            T holder = creatHolder(parent);
            holders.add(holder);
            return holder;
        }

        protected abstract void bind(int position, T holder);

        public List<T> getAllHolder() {
            return holders;
        }
    }

    public static class GroupHolder {
        private int position = 0;
        protected View ItemView;

        public int getAdapterPosition() {
            return position;
        }

        public GroupHolder(View view) {
            this.ItemView = view;
        }
    }
}
